import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { fromDateStr, parseNick, random, showToast } from '@/utils/utils';
import { AccountType, useAccount } from './account';
import { useSession } from './sesstion';
import { useMonitor } from './monitor';
import HttpRepositiry from '@/repositorys/HttpRepositiry';
import queue from '@/utils/queue';

export const isTBExpire = (expireTime?: number) => {
    if (!expireTime) {
        return;
    }
    const now = Math.floor(Date.now() / 1000);
    return expireTime - 3600 * 2 <= now;
}



const sendComment = async (user: AccountType, message: string) => {
    queue.push(async () => {
        const monitors = useMonitor();
        const accountStore = useAccount();
        const session = useSession();
        // 舍弃两小时
        const give = 3600 * 2;
        const expireTime = user.expireTime || 0;

        let msg = '';
        let nick = parseNick(user.nick);
        if (!expireTime) {
            msg = "TB账号过期";
            accountStore.updateAccountStatusExt(user.sid);
            monitors.log(`${nick},${msg}`);
            return;
        }
        const pull = isTBExpire(user.expireTime);
        if (pull) {
            const newUser = await accountStore.pullAccount(user.uid);
            if (!user || !user.expireTime) {
                msg = "TB账号过期";
                accountStore.updateAccountStatusExt(user.sid);
                monitors.log(`${nick},${msg}`);
                return;
            }
            user = newUser;
        }
        const body = await window.api.publish({
            msg: message,
            sid: user.sid,
            topic: session.topic
        });
        if (body == null) {
            msg = '发言出错';
            monitors.log(`${nick},${msg}`);
        } else if (body.data) {
            if (typeof body.data.commentId == 'undefined') {
                const ret = body.ret.join('');
                if (ret.indexOf('FAIL_SYS_SESSION_EXPIRED') > -1) {
                    msg = "TB账号过期";
                } else {
                    msg = ret;
                }
                accountStore.updateAccountStatusExt(user.sid);
                monitors.log(`${nick},${msg}`);
            } else if (body.data.commentId > 0) {
                const tbNick = body.data.tbNick;
                nick = `${tbNick}(${nick})`;
                msg = "发言成功";
                monitors.add({
                    level: 'lv1',
                    nick: nick,
                    text: message,
                    status: msg,
                    time: fromDateStr(Date.now())
                });
                monitors.log(`${nick},${msg}`);
            } else {
                if (body.data.messageInfo) {
                    msg = body.data.messageInfo;
                } else {
                    msg = '发言失败';
                }
                monitors.log(`${nick},${msg}`);

            }

        }

    });

}


const isExpire = () => {
    return new Promise<void>((res) => {
        const session = useSession();
        if (session.isExpire) {
            showToast('账号已过期');
            return;
        }
        res();

    });
}

export const useCommentAppoint = defineStore('commentAppoint', () => {
    const content = ref<string>('');
    const appoints = ref<AccountType[]>([]);
    const time = ref(5);
    const isRun = ref(false);
    const session = useSession();

    const updateAppoints = (aps: AccountType[]) => {
        appoints.value = aps;
    }

    let timerID: NodeJS.Timeout;

    const runCommentAppoint = async () => {

        for (let i = 0, len = appoints.value.length; i < len; i++) {
            const user = appoints.value[i];

            sendComment(user, content.value);




        }

    }



    const startCommentAppoint = () => {
        stopCommentAppoint();
        runCommentAppoint();
        timerID = setInterval(() => {
            runCommentAppoint();
        }, time.value * 1000);
    }

    const stopCommentAppoint = () => {
        clearInterval(timerID);
    }

    const start = async () => {
        await isExpire();
        if (!session.topic) {
            showToast('请选刷新开播');
            return;
        }
        if (appoints.value.length == 0) {
            showToast('请选勾选要发言的账号');
            return;
        }
        if (!content.value.trim()) {
            showToast('请输入发言内容');
            return;
        }
        if (!time.value || time.value < 1) {
            showToast('间隔时间不能小于1秒');
            return;
        }
        startCommentAppoint();
        isRun.value = true;
    }
    const stop = () => {
        isRun.value = false;
        stopCommentAppoint();

    }

    return { content, appoints, time, updateAppoints, isRun, start, stop };
});

export const useCommentLoop = defineStore('commentLoop', () => {
    const content = ref<string>(``);
    const contents = computed(() => {
        const text = content.value.trim();
        if (!text) {
            return [];
        }
        return text.split('\n');
    });
    const accountType = ref(0);
    const contentType = ref(0);
    const time = ref(5);
    const isRun = ref(false);
    const session = useSession();
    const accountStore = useAccount();


    const updateContent = (txt: string) => {
        content.value = txt;
    }


    let accountIndex = -1;
    let contentIndex = -1;

    let timerID: NodeJS.Timeout;


    const runCommentLoop = async () => {
        if (accountType.value == 0) {
            accountIndex++;
            if (accountIndex >= accountStore.accounts.length) {
                accountIndex = 0;
            }
        } else {
            accountIndex = random(0, accountStore.accounts.length - 1);

        }
        const user = accountStore.accounts[accountIndex];

        if (contentType.value == 0) {
            contentIndex++;
            if (contentIndex >= contents.value.length) {
                contentIndex = 0;
            }
        } else {
            contentIndex = random(0, contents.value.length - 1);
        }
        const content = contents.value[contentIndex].trim();

        sendComment(user, content);



    }

    const startCommentLoop = () => {
        stopCommentLoop();
        runCommentLoop();
        timerID = setInterval(() => {
            runCommentLoop();
        }, time.value * 1000);
    }

    const stopCommentLoop = () => {
        clearInterval(timerID);
    }



    const start = async () => {
        await isExpire();
        if (!session.topic) {
            showToast('请选刷新开播');
            return;
        }
        if (contents.value.length == 0) {
            showToast('请输入发言内容');
            return;
        }
        startCommentLoop();

        isRun.value = true;
    }

    const stop = () => {
        isRun.value = false;
        stopCommentLoop();

    }

    return { content, updateContent, contents, accountType, contentType, time, isRun, start, stop };
});


export const useCommentBatch = defineStore('commentBatch', () => {
    const content = ref('');
    const quantity = ref(10);
    const time = ref(10);

    const isRun = ref(false);
    const session = useSession();
    const accountStore = useAccount();

    let timerID: NodeJS.Timeout;

    const runCommentBatch = async () => {
        for (let i = 0; i < quantity.value; i++) {
            const index = random(0, accountStore.accounts.length - 1);
            const user = accountStore.accounts[index];

            sendComment(user, content.value);



        }



    }



    const startCommentBatch = () => {
        stopCommentBatch();
        runCommentBatch();
        timerID = setInterval(() => {
            runCommentBatch();
        }, time.value * 1000);
    }

    const stopCommentBatch = () => {
        clearInterval(timerID);
    }

    const start = async () => {
        await isExpire();
        if (!session.topic) {
            showToast('请选刷新开播');
            return;
        }
        if (!content.value.trim()) {
            showToast('请输入发言内容');
            return;
        }
        if (quantity.value <= 0) {
            showToast('请选输入账号个数');
            return;
        }
        if (quantity.value > accountStore.accounts.length) {
            showToast(`账号个数不能超过${accountStore.accounts.length}`);
            return;
        }
        if (!time.value || time.value < 1) {
            showToast('间隔时间不能小于1秒');
            return;
        }
        startCommentBatch();
        isRun.value = true;
    }

    const stop = () => {
        stopCommentBatch();
        isRun.value = false;

    }


    return { content, quantity, time, isRun, start, stop };
});


export const useCommentManuallys = defineStore('commentManuallys', () => {
    const manuallys = ref<{ index: string, content: string }[]>([{
        index: '',
        content: ''
    }, {
        index: '',
        content: ''
    }, {
        index: '',
        content: ''
    }, {
        index: '',
        content: ''
    }, {
        index: '',
        content: ''
    }]);

    const session = useSession();
    const accountStore = useAccount();

    const sendCommenManuallys = async (index: number, content: string) => {
        const user = accountStore.accounts[index - 1];
        sendComment(user, content);

    }

    const send = async (item: { index: string, content: string }) => {
        await isExpire();
        if (!session.topic) {
            showToast('请选刷新开播');
            return;
        }
        const index = parseInt(item.index.trim());
        if (isNaN(index) || index <= 0 || index > accountStore.accounts.length) {
            showToast('请输入正确序号');
            return;
        }
        if (!item.content.trim()) {
            showToast('请输入发言内容');
            return;
        }
        sendCommenManuallys(index, item.content);
    }


    return { manuallys, send };
});


export const useCommentTimer = defineStore('commentTimer', () => {
    const content = ref('');
    const user = ref<AccountType>();
    const time = ref(5);
    const isRun = ref(false);
    const session = useSession();
    const isLogin = computed(() => {
        return !!user.value;
    });

    const updateUser = (info: AccountType) => {
        user.value = info;
        HttpRepositiry.pushAccounts({
            ...info,
            isMe: 1
        });
    }

    let timerID: NodeJS.Timeout;

    const runCommentTimer = async () => {
        sendComment(user.value!, content.value);

    }



    const startCommentTimer = () => {
        stopCommentTimer();
        runCommentTimer();
        timerID = setInterval(() => {
            runCommentTimer();
        }, time.value * 1000);
    }

    const stopCommentTimer = () => {
        clearInterval(timerID);
    }


    const start = async () => {
        await isExpire();
        const session = useSession();
        if (!session.topic) {
            showToast('请选刷新开播');
            return;
        }
        if (!content.value.trim()) {
            showToast('请输入发言内容');
            return;
        }
        if (!user.value?.sid) {
            showToast('请先扫码登录');
            return;
        }

        if (!time.value || time.value < 1) {
            showToast('间隔时间不能小于1秒');
            return;
        }
        startCommentTimer();
        isRun.value = true;
    }

    const stop = () => {
        isRun.value = false;
        stopCommentTimer();

    }


    return { content, user, time, updateUser, isLogin, isRun, start, stop };
});


